package com.tangkun.environment.activity;

import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * @author tangkun
 * @Description:通用网页页面
 */

public class WebActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView titleTv;
    @BindView(R.id.webview_web)
    WebView webView;

    /**
     * 从上个界面传过来的url
     */
    private String url;
    /**
     * 从上个界面传过来的标题
     */
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        //半路径需要拼接网络链接前缀
        if (!TextUtils.isEmpty(url) && !url.contains("http")) {
            url = Session.getInstance().getH5BaseUrl() + url;
        }
        //标题展示
        if (!TextUtils.isEmpty(title)) {
            titleTv.setText(title);
        } else {
            titleTv.setText("");
        }
        WebSettings webSettings = webView.getSettings();
        webSettings.setSupportZoom(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setBuiltInZoomControls(false);// support zoom
        webSettings.setUseWideViewPort(true);// 这个很关键
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDomStorageEnabled(true);// h5兼容

        webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webView.setBackgroundColor(0);
        webView.loadUrl(url);
        // 修复链接跳转到手机自带浏览器而不是在webView上显示的问题
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            /** 跳过网站中Ssl证书错误，跳过直接登陆网站 **/
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

        });

    }

    @OnClick(R.id.back)
    public void onClick() {
        Utils.hideSoftKeyboard(WebActivity.this, back);
        JumpHelper.finish(WebActivity.this);
    }
}
